﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using ProtoBuf.Message;
using Dict.Blo;
using Dict.DataModel;

namespace UI
{
    public enum TrainTimes
    {
        One = 1,//训练1次
        Five,   //训练5次
        Ten,    //训练10次
    }

    public enum TrainType
    {
        Meterial = 1,   //材料训练
        Coin,           //金币训练
        Diamond,        //钻石训练
    }

    public class TrainPage : MonoBehaviour
    {
        public List<UILabel> propValueList;
        public List<UILabel> trainAddList;
        public UILabel trainMeteHaveNum;
        public List<UILabel> trainMeteCostNums;
        public UILabel trainCoinCostNum;
        public UILabel trainDiamondCostNum;
        public GameObject trainBtnRoot;
        public GameObject confirmOrCancleRoot;
        public GameObject btnConfirm;
        public GameObject btnCancle;
        public GameObject particlePref;
        public GameObject numParticlePref;
        public CharacterRemotePage charactorPage;

        GameObject particleObj;
        List<GameObject> numParticleList = new List<GameObject>();
        bool isLastActionConfirm = false;
        int orderCount = 0;

        string heroGuid;
        UIHero hero;
        TrainTimes curChosedTimes;
        TrainType curChosedType;

        // 存储config表里读来的常量，x档每1次消耗的东西
        int[] costMetePer;
        int costCoinPer;
        int costDiamondPer;
        string costItemId;

        void Awake()
        {
            curChosedTimes = TrainTimes.One;
            curChosedType = TrainType.Meterial;

            costMetePer = new int[3];

            //普通训练
            string[] normal = DictConfigBlo.GetHeroTrainCostNormal().Split(',');
            costMetePer[0] = int.Parse(normal[1]);
            costItemId = normal[0];
            Debug.Log(costItemId);

            //中级训练
            string[] temp1 = DictConfigBlo.GetHeroTrainCostMiddle().Split(';');
            string[] meteInfo1 = temp1[0].Split(',');
            string[] coinInfo = temp1[1].Split(',');
            costMetePer[1] = int.Parse(meteInfo1[1]);
            costCoinPer = int.Parse(coinInfo[1]);

            //高级训练
            string[] temp2 = DictConfigBlo.GetHeroTrainCostHigh().Split(';');
            string[] meteInfo2 = temp2[0].Split(',');
            string[] diamondInfo = temp2[1].Split(',');
            costMetePer[2] = int.Parse(meteInfo2[1]);
            costDiamondPer = int.Parse(diamondInfo[1]);
        }

        public void SetHero(string guid)
        {
            heroGuid = guid;
            hero = StaticData.playerData.InstPlayerData.GetUIHero(guid);

            DoDestroyParticle();
            UpdateTrainingInfo();
            UpdateCostInfo();
        }

        void UpdateTrainingInfo()
        {
            TableHeroTrainingMaxMin heroTrainMM = DictHeroTrainingMaxBlo.GetTalbeHeroTrainMaxData(hero.heroId,hero.level);
            if (heroTrainMM == null)
                return;
            AttributeQueue[] types = { AttributeQueue.Attack, AttributeQueue.Hp, AttributeQueue.PhyDefend, AttributeQueue.MagicDefend };
            int[] maxNums = { heroTrainMM.attMax, heroTrainMM.hpMax, heroTrainMM.pdefMax, heroTrainMM.mdefMax };
            for (int i = 0; i < propValueList.Count; i++)
            {
                double value = hero.Trainning.GetProp(types[i]);
                propValueList[i].text = value.ToString() + "/" + maxNums[i].ToString();
            }

            bool tempTrainEmpty = true;
            bool allPlus = true;
            for (int i = 0; i < trainAddList.Count; i++)
            {
                double value = hero.TempTrainning.GetProp(types[i]);
                if(value > 0)
                {
                    tempTrainEmpty = false;
                    trainAddList[i].text = "+" + value.ToString();
                    trainAddList[i].color = new Color((float)99 / 255, 1, (float)51 / 255);
                }
                else if (value < 0)
                {
                    allPlus = false;
                    tempTrainEmpty = false;
                    trainAddList[i].text = value.ToString();
                    trainAddList[i].color = new Color((float)246 / 255, (float)17 / 255, (float)12 / 255);
                }
                else
                {
                    trainAddList[i].text = "+0";
                    trainAddList[i].color = new Color(1, 1, 1);
                }
            }
            trainBtnRoot.SetActive(tempTrainEmpty);
            confirmOrCancleRoot.SetActive(!tempTrainEmpty);

            if(allPlus)
            {
                btnCancle.SetActive(false);
                Vector3 pos = btnConfirm.transform.localPosition;
                btnConfirm.transform.localPosition = new Vector3(0, pos.y, pos.z);
            }
            else
            {
                btnCancle.SetActive(true);
                Vector3 pos = btnConfirm.transform.localPosition;
                btnConfirm.transform.localPosition = new Vector3(-70, pos.y, pos.z);
            }

            trainMeteHaveNum.text = StaticData.playerData.GetSimpleItemCount(costItemId).ToString();
        }

        void UpdateCostInfo()
        {
            int times = 1;
            switch(curChosedTimes)
            {
                case TrainTimes.One:
                    times = 1;
                    break;
                case TrainTimes.Five:
                    times = 5;
                    break;
                case TrainTimes.Ten:
                    times = 10;
                    break;
            }

            //普通训练
            trainMeteCostNums[0].text = (costMetePer[0] * times).ToString();

            //中级训练
            trainMeteCostNums[1].text = (costMetePer[1] * times).ToString();
            trainCoinCostNum.text = (costCoinPer * times).ToString();

            //高级训练
            trainMeteCostNums[2].text = (costMetePer[2] * times).ToString();
            trainDiamondCostNum.text = (costDiamondPer * times).ToString();
        }

        public void OnTrainTimes(GameObject obj)
        {
            switch(obj.name)
            {
                case "1times":
                    curChosedTimes = TrainTimes.One;
                    break;
                case "5times":
                    curChosedTimes = TrainTimes.Five;
                    break;
                case "10times":
                    curChosedTimes = TrainTimes.Ten;
                    break;
            }

            UpdateCostInfo();
        }

        public void OnTrainType(GameObject obj)
        {
            switch (obj.name)
            {
                case "checkN":
                    curChosedType = TrainType.Meterial;
                    break;
                case "checkM":
                    curChosedType = TrainType.Coin;
                    break;
                case "checkH":
                    curChosedType = TrainType.Diamond;
                    break;
            }
        }

        public void OnTrainBtn()
        {
            if(!CheckResource())
            {
                return;
            }
            CSWarriorTraining msg = new CSWarriorTraining();
            msg.guid = heroGuid;
            msg.numType = (int)curChosedTimes;
            msg.costType = (int)curChosedType;

            NetAPI.SendHttp(OpDefine.CSWarriorTraining,msg,TrainCallback);
        }

        void TrainCallback(NetWork.Packets.Packet packet,bool bSuccess)
        {
            if(bSuccess)
            {
                PlayNumEffect();

                SCWarriorTraining msg = packet.kBody as SCWarriorTraining;
                StaticData.playerData.Delete(msg.cost);
                StaticData.playerData.UpdateHero(msg.guid);
                
                hero = StaticData.playerData.InstPlayerData.GetUIHero(heroGuid);
                UpdateTrainingInfo();
            }
        }

        public void OnConfirmBtn()
        {
            isLastActionConfirm = true;
            CSWarriorTrainingReplace msg = new CSWarriorTrainingReplace();
            msg.guid = heroGuid;
            msg.result = 1;

            NetAPI.SendHttp(OpDefine.CSWarriorTrainingReplace, msg, ConfirmCallback);
        }

        public void OnCancleBtn()
        {
            isLastActionConfirm = false;
            CSWarriorTrainingReplace msg = new CSWarriorTrainingReplace();
            msg.guid = heroGuid;
            msg.result = 0;

            NetAPI.SendHttp(OpDefine.CSWarriorTrainingReplace, msg, ConfirmCallback);
        }

        void ConfirmCallback(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                if (isLastActionConfirm)
                    PlayCharactorEffect();

                SCWarriorTrainingReplace msg = packet.kBody as SCWarriorTrainingReplace;
                StaticData.playerData.Delete(msg.cost);
                StaticData.playerData.UpdateHero(msg.result);

                hero = StaticData.playerData.InstPlayerData.GetUIHero(heroGuid);
                UpdateTrainingInfo();
            }
        }
        
        bool CheckResource()
        {
            int times = 1;
            switch (curChosedTimes)
            {
                case TrainTimes.One:
                    times = 1;
                    break;
                case TrainTimes.Five:
                    times = 5;
                    break;
                case TrainTimes.Ten:
                    times = 10;
                    break;
            }
            int itemNum = costMetePer[(int)curChosedType - 1] * times;
            int coinNum = 0;
            int diamondNum = 0;
            if (curChosedType == TrainType.Coin)
                coinNum = costCoinPer * times;
            if (curChosedType == TrainType.Diamond)
                diamondNum = costDiamondPer * times;

            if(StaticData.playerData.GetSimpleItemCount(costItemId) < itemNum)
            {
                BoxManager.CreatePopupTextBox(TableTextBlo.GetText("name_" + costItemId).Replace("\\r", "\r").Replace("\\n", "\n")
                +TableTextBlo.GetText("not_enough").Replace("\\n", "\n").Replace("\\r", "\r"));
                return false;
            }

            if (StaticData.playerData.coin < coinNum)
            {
                BoxManager.CreatePopupTextBox(TableTextBlo.GetText("coin_lack").Replace("\\n", "\n").Replace("\\r", "\r"));
                return false;
            }

            if (StaticData.playerData.diamond < diamondNum)
            {
                BoxManager.CreatePopupTextBox(TableTextBlo.GetText("diamond_lack").Replace("\\n", "\n").Replace("\\r", "\r"));
                return false;
            }

            return true;
        }

        void PlayCharactorEffect()
        {
            //人物身上的特效
            AudioManager.Instance.PlayUIAudio("tupojindutiaoFujia");
            if (particleObj != null)
                Destroy(particleObj);
            particleObj = Instantiate(particlePref);
            particleObj.transform.parent = gameObject.transform;
            particleObj.transform.localPosition = new Vector3(charactorPage.heroPosition.transform.localPosition.x, charactorPage.heroPosition.transform.localPosition.y + 250,-400);
            particleObj.transform.localScale = Vector3.one;
            particleObj.SetActive(true);

            StartCoroutine(DestroyParticle());
        }

        void PlayNumEffect()
        {
            //数值上面的特效
            foreach (var item in numParticleList)
            {
                Destroy(item);
            }
            numParticleList.Clear();
            foreach (var item in trainAddList)
            {
                GameObject particle = Instantiate(numParticlePref);
                particle.transform.parent = item.transform;
                particle.transform.localPosition = Vector3.zero;
                particle.transform.localScale = Vector3.one;
                particle.SetActive(true);
                numParticleList.Add(particle);
            }
            AudioManager.Instance.PlayUIAudio("juesexunlian");
            StartCoroutine(DestroyParticle());
        }

        IEnumerator DestroyParticle()
        {
            orderCount++;
            yield return new WaitForSeconds(2.5f);

            orderCount--;
            if (orderCount <= 0)
                DoDestroyParticle();
        }

        void DoDestroyParticle()
        {
            foreach (var item in numParticleList)
            {
                Destroy(item);
            }
            numParticleList.Clear();
            
            if (particleObj != null)
                Destroy(particleObj);
        }
    }
}
